<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model.trim="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeRef"
          highlight-current
          node-key="id"
          :expand-on-click-node="false"
          default-expand-all
          :data="depts"
          :props="defaultProps"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class-name="opeate-tools" type="flex" justify="end">
          <el-button v-auth="'add'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showImportDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmp">excel导出</el-button>
        </el-row>
        <!--表格-->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{row}">
              <!--              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />-->
              <!--              <span v-else class="username">{{ row.username?.[0] }}</span>-->
              <el-image :preview-src-list="[row.staffPhoto]" :src="row.staffPhoto" style="width: 30px; height:30px">
                <!--如果图片加载不出来，就会加载插槽里面的内容-->
                <template #error>
                  <span class="username">{{ row.username?.[0] }}</span>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="editRole(row.id)">角色</el-button>
              <el-popconfirm v-auth="'delete'" style="margin-left: 10px;" title="是否确认删除当前员工？" @onConfirm="delEmp(row.id)">
                <template #reference>
                  <el-button size="mini" type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev,pager,next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!--    导入excel组件-->
    <import-excel :show-excel-dialog.sync="showImportDialog" @uploadSuccess="getEmpList" />
    <!--角色配置弹层结构-->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>

      <template #footer>
        <el-button size="mini">取消</el-button>
        <el-button size="mini" type="primary" @click="btnOk">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { getDepts } from '@/api/deparment'
import { transListToTree } from '@/utils'
import {
  assignRole,
  delEmployee,
  exportToExcel,
  getAllEnableRoleList,
  getEmployeeDetail,
  getEmployeesList
} from '@/api/employee'
// 用到那个包引入哪个包
import throttle from 'lodash/throttle'
import ImportExcel from '@/views/employee/components/import-excel.vue'

export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      roleIds: [],
      showRoleDialog: false,
      roleList: [], // 所有可用的角色数据
      showImportDialog: false,
      queryParams: {
        departmentId: null, // 当前选中的部门的id
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      total: 0,
      list: [],
      depts: [],
      defaultProps: {
        // 指定展示的字段名称
        label: 'name',
        // 子节点的属性
        children: 'children'
      },
      currentId: null
    }
  },
  created() {
    this.getDepart()
    this.getAllRoleList() // 获取所有的默认的角色信息
  },
  methods: {
    async btnOk() {
      // 开始提交数据了
      // 提交数据的时候就可以用到当前对应的角色id
      await assignRole({
        id: this.currentId, // 修改哪个员工的数据
        roleIds: this.roleIds // 对应的最新的角色数据
      })
      this.$message.success('修改角色信息成功')
      this.showRoleDialog = false
    },
    // 点击编辑的时候记录当前点击的员工id
    async editRole(id) {
      this.currentId = id
      // 把当前点击的员工的id进行记录 >> 提交数据的时候需要用到这个id
      // 获取到当前点击的员工对应的详细信息
      // console.log(id)
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds // 当前员工拥有的所有的角色id列表
      this.showRoleDialog = true
    },
    async getAllRoleList() {
      this.roleList = await getAllEnableRoleList()
    },
    async delEmp(id) {
      await delEmployee(id)
      this.$message.success('删除成功')
      // 重新获取员工数据
      await this.getEmpList()
    },
    async exportEmp() {
      const res = await exportToExcel()
      FileSaver.saveAs(res, '员工数据111')
    },
    changeValue: throttle(function() {
      this.queryParams.page = 1
      this.getEmpList()
    }, 3000),
    changePage(page) {
      this.queryParams.page = page // 把切换之后最新的页码数赋值给请求参数之后再发送请求
      this.getEmpList()
    },
    // 1、初始的时候调用获取员工列表的方法
    // 2、切换的时候调用获取员工列表的方法
    selectNode(node) {
      // console.log(node) // 当前点击的部门的数据
      //   切换之后的最新的部门id继续进行记录 >> 获取右侧的员工数据
      this.queryParams.departmentId = node.id
      // 切换之后把页码数重置为1之后再请求接口
      this.queryParams.page = 1
      this.getEmpList()
    },
    async getDepart() {
      this.depts = transListToTree(await getDepts(), 0)
      this.queryParams.departmentId = this.depts[0].id // 默认把第一个节点的id进行记录
      // 默认把第一个节点选中
      // this.$refs.treeRef.setCurrentKey(this.depts[0].id)
      // 等到tree组件里面的数据渲染出来之后，再去设置高亮的节点
      this.$nextTick(() => {
        this.$refs.treeRef.setCurrentKey(this.depts[0].id)
      })
      // 初始化的时候获取员工数据
      this.getEmpList()
    },
    async getEmpList() {
      const res = await getEmployeesList(this.queryParams) // {departmentId}
      this.list = res.rows
      this.total = res.total
    }
  }
}
</script>

<style lang="scss" scoped>

.app-container {
  background: #fff;
  display: flex;

  ::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background: #04c9be;
    color: white;
    transition: 0.2s;
  }

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}

</style>
